const app = getApp()
const WXAPI = require('../../wxapi/main')

Page({

  data: {
    totalScoreToPay: 0,
    goodsList: [],
    // isNeedLogistics: 0, // 是否需要物流信息
    allGoodsPrice: 0,
    // yunPrice: 0,
    allGoodsAndYunPrice: 0,
    goodsJsonStr: "",
    // pingtuanOpenId: undefined, //拼团的话记录团号

    // hasNoCoupons: true,
    // coupons: [],
    // youhuijine: 0, //优惠券金额
    // curCoupon: null // 当前选择使用的优惠券
    orderList: []
  },

  
  onLoad: function(e) {

    var that = this;
    var shopList = [];

    //购物车下单
    var shopCarInfoMem = wx.getStorageSync('shopCarInfo');

    // 砍价
    // that.data.kjId = shopCarInfoMem.kjId;

    if (shopCarInfoMem && shopCarInfoMem.shopList) {
      // shopList = shopCarInfoMem.shopList
      shopList = shopCarInfoMem.shopList.filter(entity => {
        return entity.active;
      });
    }

    that.setData({
      goodsList: shopList,
    });
    that.initShippingAddress();


  },

  onShow: function() {
  
  },


  getDistrictId: function(obj, aaa) {
    if (!obj) {
      return "";
    }
    if (!aaa) {
      return "";
    }
    return aaa;
  },

  createOrder: function(e) {
    var that = this;
    var userInfo = wx.getStorageSync('userInfo') // 用户登录 token
    var remark = ""; // 备注信息
    if (e) {
      remark = e.detail.value.remark; // 备注信息
    }


    // 完成postData
    var postData = {
      token: userInfo.token,
      goodsJsonStr: that.data.goodsJsonStr,
      oNote: remark,
      oState: 0
    };


    // 如果没有地址
    if (that.data.isNeedLogistics > 0) {
      if (!that.data.curAddressData) {
        wx.hideLoading();
        wx.showModal({
          title: '错误',
          content: '请先设置您的收货地址！',
          showCancel: false
        })
        return;
      }
    }

    console.log("postData", postData);


    // 不交互版=====================

    /* 
    let dishList = wx.getStorageSync('dishList');
    
    let orderList = wx.getStorageSync('orderList');


    var order = {
      oid: 1,
      oNote: remark,
      dishList: dishList,
      oState: 0, // 
      oTotalPrice: that.data.allGoodsAndYunPrice
    };

    console.log("orderList", orderList)

    if (!orderList){
      let orderList = [];
      // console.log("orderList", orderList)
      orderList.push(order);
      console.log("orderList", orderList)
      wx.setStorageSync('orderList', orderList);
      // 去除购物车信息
    wx.removeStorageSync('shopCarInfo');
      if (wx.getStorageSync('orderList')) {
        wx.reLaunch({
          url: '/pages/my/index',
        });
      }
    } else {
     orderList.push(order);
     wx.setStorageSync('orderList', orderList);
     // 去除购物车信息
      wx.removeStorageSync('shopCarInfo');
     if (wx.getStorageSync('orderList')) {
      wx.reLaunch({
        url: '/pages/my/index',
      });
    } 
    */

   // ======================不交互版



 // 交互版================

    wx.request({
      url: 'http://localhost:9111/order/insertOrder', // 端口可能要改
      data: {
        orders: postData.goodsJsonStr,
        token: postData.token,
        oNote: postData.oNote
      },
      header: {
        'content-type': 'application/json'
      },
      success: function (res) {
        if (res.data.status == "200") {
          if (res.data.error == true) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          } else {

            // 交互成功---

            let dishList = wx.getStorageSync('dishList');
            let orderList = wx.getStorageSync('orderList');

            var order = {
              oid: res.data.data,
              oNote: remark,
              dishList: dishList,
              oState: 0, // 
              oTotalPrice: that.data.allGoodsAndYunPrice
            };

            console.log("orderList", orderList)

            // 不存在订单list
            if (!orderList){
              let orderList = [];
              // console.log("orderList", orderList)
              orderList.push(order);
              console.log("orderList", orderList)
              wx.setStorageSync('orderList', orderList);
              
              // 去除购物车信息
              wx.removeStorageSync('shopCarInfo');
              if (wx.getStorageSync('orderList')) {
                wx.reLaunch({
                  url: '/pages/my/index',
                });
              }
            } 
            // 存在订单list
            else {
              orderList.push(order);
              wx.setStorageSync('orderList', orderList);
              // 去除购物车信息
                wx.removeStorageSync('shopCarInfo');
              if (wx.getStorageSync('orderList')) {
                wx.reLaunch({
                  url: '/pages/my/index',
                });
              }
              
            } 
          }
            // ---交互成功
        } else {
          // 失败 ---
          wx.showToast({
            title: '服务器出现错误',
            icon: 'none',
            duration: 2000
          })
          // ----失败
        }
      }
    })

    // ==================交互版



  
    
  },

  // 初始化收货地址
  initShippingAddress: function() {
    var that = this;


    let linkMan = "张三";
    let mobile = "1235636";
    let address = "金陵科技学院北区05b";
    

    let userInfo = {};
    userInfo = wx.getStorageSync('userInfo');

    // 收货信息
    var curAddressData = {
      linkMan: userInfo.userName,
      mobile: userInfo.phone,
      address: userInfo.address
    }

    that.setData({
      // 收货地址
      curAddressData: curAddressData
    });

    that.processYunfei();
  },

  // 处理运费
  processYunfei: function() {
    var that = this;
    var goodsList = this.data.goodsList;
    
    console.log("processYunfei, goodsList", goodsList);

    var goodsJsonStr = "[";
    var isNeedLogistics = 0;
    var allGoodsPrice = 0;


    let inviter_id = 0;
    let inviter_id_storge = wx.getStorageSync('referrer');

    if (inviter_id_storge) {
      inviter_id = inviter_id_storge;
    }

    
    let userInfo = wx.getStorageSync('userInfo');
    let uid = userInfo.userId;

    var dishList = [];

    for (let i = 0; i < goodsList.length; i++) {
      let carShopBean = goodsList[i];

      if (carShopBean.logistics) {
        isNeedLogistics = 1;
      }

      allGoodsPrice += carShopBean.price * carShopBean.number;

      var goodsJsonStrTmp = '';
      if (i > 0) {
        goodsJsonStrTmp = ",";
      }

      var mid = parseInt(carShopBean.goodsId/100);
      
      goodsJsonStrTmp += '{"uid":' + uid + ',"did":' + carShopBean.goodsId + ',"mid":' + mid +  ',"num":' + carShopBean.number + ',"price":' + carShopBean.price + '}';
      goodsJsonStr += goodsJsonStrTmp;

      let totalPrice = carShopBean.number * carShopBean.price;

      dishList[i] = {
        uid: uid,
        mid: mid,
        did: carShopBean.goodsId,
        dName: carShopBean.name,
        dImage: carShopBean.pic,
        number: carShopBean.number,
        price: carShopBean.price,
        totalPrice: totalPrice
      }

    }
    
    that.setData({
      allGoodsAndYunPrice: allGoodsPrice,
    })

    // 可删
    wx.setStorageSync('dishList', dishList)
    

    goodsJsonStr += "]";
    
    console.log('goodsJsonStr', goodsJsonStr)

    that.setData({
      // isNeedLogistics: isNeedLogistics,
      goodsJsonStr: goodsJsonStr
    });

    console.log("开始创建订单!")


    // 菜品列表
   
    // that.createOrder();

  },


  addAddress: function() {
    wx.navigateTo({
      url: "/pages/address-add/index"
    })
  },


  selectAddress: function() {
    wx.navigateTo({
      url: "/pages/select-address/index"
    })
  },

  getMyCoupons: function() {
    var that = this;
    WXAPI.myCoupons({
      // token: wx.getStorageSync('token'),
      status: 0
    }).then(function(res) {
      if (res.code == 0) {
        var coupons = res.data.filter(entity => {
          return entity.moneyHreshold <= that.data.allGoodsAndYunPrice;
        });
        if (coupons.length > 0) {
          that.setData({
            hasNoCoupons: false,
            coupons: coupons
          });
        }
      }
    })
  },
  bindChangeCoupon: function(e) {
    const selIndex = e.detail.value[0] - 1;
    if (selIndex == -1) {
      this.setData({
        youhuijine: 0,
        curCoupon: null
      });
      return;
    }
    //console.log("selIndex:" + selIndex);
    this.setData({
      youhuijine: this.data.coupons[selIndex].money,
      curCoupon: this.data.coupons[selIndex]
    });
  }
})